﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;

namespace CEED.Utils
{
    public class SEEDinfo
    {
        public string Magic;
        public int Count;
        public List<SEEDEntry> Entries = new List<SEEDEntry>();

        public SEEDinfo(string path)
        {
            using (FileStream fs = File.OpenRead(path))
            {
                FromStream(fs);
            }
        }
        public SEEDinfo(Stream stream)
        {
            FromStream(stream);
        }
        public void FromStream(Stream stream)
        {
            BinaryReader reader = new BinaryReader(stream);
            Magic = new string(reader.ReadChars(4));
            if (Magic != "SEED")
                throw new Exception("不是有效的seedinfo文件");
            Count = reader.ReadInt32();

            for (int i = 0; i < Count; i++)
            {
                Entries.Add(new SEEDEntry(reader.ReadBytes(8)));
            }
            for (int i = 0; i < Count; i++)
            {
                Entries[i].SEED = reader.ReadBytes(16);
            }
            for (int i = 0; i < Count; i++)
            {
                Entries[i] = new SEEDEntry(Entries[i]);
            }
        }
    }
    public class SEEDEntry
    {
        public byte[] TitleID;
        public byte[] SEED;
        public byte[] KeyY;
        public uint Checksum;

        public SEEDEntry(byte[] titleid)
        {
            TitleID = titleid;
            SEED = new byte[16];
        }
        public SEEDEntry(SEEDEntry entry)
        {
            TitleID = entry.TitleID;
            SEED = entry.SEED;
            byte[] temp;
            SHA256 sha256 = new SHA256Managed();

            //Compute Checksum
            temp = new byte[24];
            Array.Copy(SEED, 0, temp, 0, 16);
            Array.Copy(TitleID, 0, temp, 16, 8);
            Checksum = BitConverter.ToUInt32(sha256.ComputeHash(temp), 0);
        }
        public SEEDEntry(SEEDEntry entry, byte[] oldKeyY)
        {
            TitleID = entry.TitleID;
            SEED = entry.SEED;
            KeyY = oldKeyY;

            //Compute new KeyY
            byte[] temp = new byte[32];
            Array.Copy(oldKeyY, 0, temp, 0, 16);
            Array.Copy(SEED, 0, temp, 16, 16);
            SHA256 sha256 = new SHA256Managed();
            Array.Copy(sha256.ComputeHash(temp), 0, KeyY, 0, 16);
        }
    }
}
